// Background script for YouTube Cookie Exporter
// 处理扩展的后台任务

console.log('YouTube Cookie Exporter background script 开始加载');

let autoExportTimer = null;
let isAutoExporting = false;

// Service Worker保活机制
let keepAliveInterval;

function startKeepAlive() {
    if (keepAliveInterval) {
        clearInterval(keepAliveInterval);
    }
    
    // 每25秒发送一个简单的操作来保持service worker活跃
    keepAliveInterval = setInterval(() => {
        chrome.storage.local.get(['keepAlive'], (result) => {
            console.log('Service Worker保活检查');
        });
    }, 25000);
    
    console.log('Service Worker保活机制已启动');
}

// 启动保活机制
startKeepAlive();

chrome.runtime.onInstalled.addListener(function(details) {
    console.log('YouTube Cookie Exporter background script 启动');
    if (details.reason === 'install') {
        console.log('YouTube Cookie Exporter 已安装');
        // 初始化配置
        chrome.storage.sync.set({
            autoExportEnabled: false,
            exportInterval: 120
        });
    } else if (details.reason === 'update') {
        console.log('YouTube Cookie Exporter 已更新');
    }
    
    // 启动时检查是否需要启动自动刷新
    console.log('准备检查自动刷新设置...');
    startAutoRefreshIfEnabled();
});

// 监听来自popup的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log('收到消息:', request.action);
    
    if (request.action === 'ping') {
        console.log('收到ping消息，准备响应');
        sendResponse({success: true, message: 'background script正常运行'});
        return true; // 表示我们会同步响应
    } else if (request.action === 'exportCookies') {
        exportCookiesToFile(request.domain)
            .then(result => {
                sendResponse({success: true, data: result});
            })
            .catch(error => {
                sendResponse({success: false, error: error.message});
            });
        return true; // 保持消息通道开放
    } else if (request.action === 'updateAutoExportConfig') {
        console.log('收到updateAutoExportConfig消息');
        updateAutoExportConfig(request.config);
        sendResponse({success: true});
    } else if (request.action === 'pageRefresh') {
        // 页面刷新时，只记录日志，不立即导出
        console.log('检测到YouTube页面刷新，等待页面加载完成');
        sendResponse({success: true});
    } else if (request.action === 'pageLoaded') {
        // 页面加载完成，执行自动导出
        console.log('YouTube页面加载完成，开始自动导出');
        performPageLoadExport();
        sendResponse({success: true});
    } else if (request.action === 'testAutoRefresh') {
        // 测试自动刷新
        console.log('开始测试自动刷新');
        // 强制重置状态
        isAutoExporting = false;
        performAutoRefresh()
            .then(() => {
                sendResponse({success: true});
            })
            .catch(error => {
                console.error('测试自动刷新失败:', error);
                isAutoExporting = false; // 确保重置状态
                sendResponse({success: false, error: error.message});
            });
        return true; // 保持消息通道开放
    } else if (request.action === 'testRefresh') {
        // 测试刷新功能
        console.log('开始测试刷新功能');
        chrome.tabs.query({url: ['https://*.youtube.com/*', 'https://*.youtube-nocookie.com/*']}, function(tabs) {
            if (tabs.length === 0) {
                sendResponse({success: false, error: '未找到YouTube标签页'});
                return;
            }
            
            chrome.tabs.reload(tabs[0].id, function() {
                if (chrome.runtime.lastError) {
                    sendResponse({success: false, error: chrome.runtime.lastError.message});
                } else {
                    sendResponse({success: true});
                }
            });
        });
        return true;
    } else if (request.action === 'testTimer') {
        // 测试定时器功能（用10秒间隔）
        console.log('开始测试定时器功能');
        stopAutoRefresh();
        
        let testCount = 0;
        autoExportTimer = setInterval(() => {
            testCount++;
            const currentTime = new Date().toLocaleTimeString();
            console.log(`[${currentTime}] 测试定时器第${testCount}次触发`);
            
            if (testCount >= 3) {
                console.log('测试定时器完成，停止');
                stopAutoRefresh();
            }
        }, 10000); // 10秒间隔
        
        sendResponse({success: true, message: '测试定时器已启动，每10秒触发一次，共3次'});
    } else if (request.action === 'resetAutoExport') {
        // 重置自动刷新状态
        isAutoExporting = false;
        console.log('自动刷新状态已重置');
        sendResponse({success: true});
    }
});

// 启动自动刷新（如果启用）
function startAutoRefreshIfEnabled() {
    console.log('检查是否需要启动自动刷新...');
    chrome.storage.sync.get(['autoExportEnabled', 'exportInterval'], function(config) {
        console.log('自动刷新配置:', config);
        if (config.autoExportEnabled) {
            console.log('自动刷新已启用，开始启动');
            startAutoRefresh(config.exportInterval);
        } else {
            console.log('自动刷新未启用');
        }
    });
}

// 更新自动刷新配置
function updateAutoExportConfig(config) {
    console.log('收到配置更新请求:', config);
    if (config.autoExportEnabled) {
        console.log('启用自动刷新，间隔:', config.exportInterval);
        startAutoRefresh(config.exportInterval);
    } else {
        console.log('禁用自动刷新');
        stopAutoRefresh();
    }
}

// 启动自动刷新
function startAutoRefresh(intervalMinutes) {
    stopAutoRefresh(); // 先停止现有的定时器
    
    console.log(`启动自动刷新，间隔: ${intervalMinutes}分钟`);
    
    // 保存当前时间作为开始时间
    const now = new Date();
    chrome.storage.local.set({
        lastExportTime: now.getTime(),
        exportInterval: intervalMinutes
    });
    
    // 设置定时器，每隔指定时间执行一次刷新
    autoExportTimer = setInterval(async () => {
        const currentTime = new Date().toLocaleTimeString();
        console.log(`[${currentTime}] 定时器触发，开始自动刷新`);
        
        if (isAutoExporting) {
            console.log('自动刷新正在进行中，跳过本次');
            return;
        }
        
        try {
            await performAutoRefresh();
            
            // 更新最后刷新时间
            const refreshTime = new Date();
            chrome.storage.local.set({
                lastExportTime: refreshTime.getTime()
            });
            console.log(`[${currentTime}] 自动刷新执行完成`);
        } catch (error) {
            console.error('自动刷新执行失败:', error);
        }
        
    }, intervalMinutes * 60 * 1000);
    
    console.log(`自动刷新已启动，将在${intervalMinutes}分钟后首次执行`);
}

// 停止自动刷新
function stopAutoRefresh() {
    if (autoExportTimer) {
        clearInterval(autoExportTimer);
        autoExportTimer = null;
        console.log('自动刷新已停止');
    }
}

// 执行页面加载后的自动导出
async function performPageLoadExport() {
    if (isAutoExporting) return;
    
    isAutoExporting = true;
    console.log('开始页面加载后的自动导出...');
    
    try {
        // 获取YouTube相关的cookies
        const allCookies = await chrome.cookies.getAll({});
        console.log(`总共找到 ${allCookies.length} 个cookie`);
        
        const youtubeCookies = allCookies.filter(cookie => 
            cookie.domain.includes('youtube.com') || 
            cookie.domain.includes('youtube-nocookie.com') ||
            cookie.domain.includes('google.com') ||
            cookie.domain.includes('googleapis.com')
        );
        
        console.log(`其中YouTube相关cookie: ${youtubeCookies.length} 个`);
        
        if (youtubeCookies.length === 0) {
            console.log('未找到YouTube相关Cookie，跳过自动导出');
            isAutoExporting = false;
            return;
        }
        
        // 去重cookies
        const uniqueCookies = [];
        const seen = new Set();
        
        youtubeCookies.forEach(cookie => {
            const key = `${cookie.name}-${cookie.domain}`;
            if (!seen.has(key)) {
                seen.add(key);
                uniqueCookies.push(cookie);
            }
        });
        
        // 生成Netscape格式的cookie文件
        const netscapeContent = generateNetscapeFormat(uniqueCookies, '.youtube.com');
        
        const now = new Date();
        const timestamp = now.toISOString().slice(0, 19).replace(/:/g, '-').replace('T', '_');
        const filename = `youtube_cookies_auto_${timestamp}.txt`;
        
        // 使用data URL来下载文件
        const dataUrl = 'data:text/plain;charset=utf-8,' + encodeURIComponent(netscapeContent);
        
        const downloadResult = await chrome.downloads.download({
            url: dataUrl,
            filename: filename,
            saveAs: false // 自动下载，不询问保存位置
        });
        
        console.log('下载请求已发送，下载ID:', downloadResult);
        
        // 保存最后导出时间
        await chrome.storage.local.set({
            lastExportTime: now.getTime(),
            exportInterval: await getExportInterval()
        });
        
        console.log(`页面加载后自动导出完成: ${uniqueCookies.length}个Cookie已保存到 ${filename}`);
        
    } catch (error) {
        console.error('页面加载后自动导出失败:', error);
    } finally {
        isAutoExporting = false;
    }
}

// 执行自动刷新
async function performAutoRefresh() {
    if (isAutoExporting) return;
    
    isAutoExporting = true;
    console.log('开始自动刷新YouTube页面...');
    
    try {
        // 检查是否有YouTube标签页
        console.log('正在查找YouTube标签页...');
        const tabs = await chrome.tabs.query({url: ['https://*.youtube.com/*', 'https://*.youtube-nocookie.com/*']});
        console.log(`找到 ${tabs.length} 个YouTube标签页`);
        
        if (tabs.length === 0) {
            console.log('未找到YouTube标签页，跳过自动刷新');
            isAutoExporting = false;
            return;
        }

        // 刷新YouTube页面
        console.log(`准备刷新标签页 ${tabs[0].id}，URL: ${tabs[0].url}`);
        await refreshYouTubePage(tabs[0].id);
        
        console.log('自动刷新完成，页面刷新后会自动导出Cookie');
        
    } catch (error) {
        console.error('自动刷新失败:', error);
    } finally {
        isAutoExporting = false;
    }
}

// 刷新YouTube页面
async function refreshYouTubePage(tabId) {
    return new Promise((resolve, reject) => {
        // 直接刷新页面，不通过content script
        chrome.tabs.reload(tabId, function() {
            if (chrome.runtime.lastError) {
                console.error('刷新页面失败:', chrome.runtime.lastError.message);
                reject(new Error(chrome.runtime.lastError.message));
            } else {
                console.log('页面刷新成功');
                resolve();
            }
        });
    });
}

// 获取导出间隔
function getExportInterval() {
    return new Promise((resolve) => {
        chrome.storage.sync.get(['exportInterval'], function(config) {
            resolve(config.exportInterval || 120);
        });
    });
}

// 导出cookies到文件
async function exportCookiesToFile(domain) {
    return new Promise((resolve, reject) => {
        chrome.cookies.getAll({domain: domain}, function(cookies) {
            if (chrome.runtime.lastError) {
                reject(new Error(chrome.runtime.lastError.message));
                return;
            }

            if (cookies.length === 0) {
                reject(new Error('未找到任何Cookie'));
                return;
            }

            // 生成Netscape格式的cookie内容
            const netscapeContent = generateNetscapeFormat(cookies, domain);
            
            const now = new Date();
            const timestamp = now.toISOString().slice(0, 19).replace(/:/g, '-').replace('T', '_');
            const filename = `youtube_cookies_${timestamp}.txt`;
            
            // 使用data URL来下载文件
            const dataUrl = 'data:text/plain;charset=utf-8,' + encodeURIComponent(netscapeContent);
            
            chrome.downloads.download({
                url: dataUrl,
                filename: filename,
                saveAs: true
            }, function(downloadId) {
                if (chrome.runtime.lastError) {
                    reject(new Error(chrome.runtime.lastError.message));
                } else {
                    resolve({
                        downloadId: downloadId,
                        filename: filename,
                        cookieCount: cookies.length
                    });
                }
            });
        });
    });
}

// 生成Netscape格式的cookie内容
function generateNetscapeFormat(cookies, domain) {
    let content = '# Netscape HTTP Cookie File\n';
    content += '# This is a generated file! Do not edit.\n';
    content += '# Generated by YouTube Cookie Exporter\n';
    content += `# Domain: ${domain}\n`;
    content += `# Generated: ${new Date().toISOString()}\n\n`;
    
    cookies.forEach(cookie => {
        const cookieDomain = cookie.domain.startsWith('.') ? cookie.domain : '.' + cookie.domain;
        const path = cookie.path || '/';
        const secure = cookie.secure ? 'TRUE' : 'FALSE';
        const expires = cookie.expirationDate ? Math.floor(cookie.expirationDate) : '0';
        const name = cookie.name;
        const value = cookie.value;
        
        // Netscape格式: domain, domain_specified, path, secure, expires, name, value
        content += `${cookieDomain}\t${cookieDomain.includes('.') ? 'TRUE' : 'FALSE'}\t${path}\t${secure}\t${expires}\t${name}\t${value}\n`;
    });
    
    return content;
}

// 监听下载完成事件
chrome.downloads.onChanged.addListener(function(downloadDelta) {
    if (downloadDelta.state && downloadDelta.state.current === 'complete') {
        console.log('Cookie文件下载完成:', downloadDelta.id);
    }
});

// 扩展启动时检查自动刷新
chrome.runtime.onStartup.addListener(function() {
    console.log('扩展启动，检查自动刷新设置');
    startAutoRefreshIfEnabled();
});

// 监听存储变化
chrome.storage.onChanged.addListener(function(changes, namespace) {
    if (namespace === 'sync' && (changes.autoExportEnabled || changes.exportInterval)) {
        console.log('自动刷新配置已更改');
        chrome.storage.sync.get(['autoExportEnabled', 'exportInterval'], function(config) {
            updateAutoExportConfig(config);
        });
    }
});
